package com.cloudcentral.filter;

import com.cloudcentral.config.SMSAuthenticationToken;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * Create by Administrator
 * 2023/11/10 10:28
 */
public class SMSAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  private String phoneParameter = "phone";
  private String codeParameter = "code";

  public SMSAuthenticationFilter(RequestMatcher matcher) {
    super(matcher);
  }

  public SMSAuthenticationFilter(RequestMatcher matcher, AuthenticationManager authenticationManager) {
    super(matcher, authenticationManager);
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    // 获取手机号、用户输入的验证码请求参数
    String phone = request.getParameter(phoneParameter), code = request.getParameter(codeParameter);
    SMSAuthenticationToken authRequest = new SMSAuthenticationToken((phone != null ? phone : "").trim(), (code != null ? code : "").trim());
    authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    // 认证
    return this.getAuthenticationManager().authenticate(authRequest);
  }

  public void setMatcher(RequestMatcher matcher) {
    this.setRequiresAuthenticationRequestMatcher(matcher);
  }

  public void setPhoneParameter(String phoneParameter) {
    this.phoneParameter = phoneParameter;
  }

  public void setCodeParameter(String codeParameter) {
    this.codeParameter = codeParameter;
  }
}
